package payrechargelogic

import (
	"context"
	"errors"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/config"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/service"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type RechargeEventAddBalanceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRechargeEventAddBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeEventAddBalanceLogic {
	return &RechargeEventAddBalanceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// RechargeEventAddBalance 活动充值
func (l *RechargeEventAddBalanceLogic) RechargeEventAddBalance(in *rpc.RechargeEventAddBalanceRequest) (*rpc.RechargeEventAddBalanceResponse, error) {
	if in.Amount < 0 {
		return nil, errors.New("invalid parameter amount")
	}
	ret := &rpc.RechargeEventAddBalanceResponse{}

	rb := &rpc.BalanceIncreaseRequest{
		UserId:      in.UserId,
		Amount:      in.Amount,
		OperatorId:  0,
		TypeId:      config.TYPE_ACTIVITY_REWARD,
		SourceId:    strconv.FormatInt(in.Time, 10),
		Description: "activity reward",
		ValidMark:   0,
	}
	balanceIncrease, err := service.BalanceIncrease(l.ctx, l.svcCtx, rb, nil)
	if err != nil {
		return nil, err
	}
	ret.WalletLogId = balanceIncrease.Id
	// err := l.svcCtx.Db.Transaction(func(tx *gorm.DB) error {
	//	// 开启事务
	//	// 加余额
	//	userWallet, err := user.NewWalletModel(l.ctx, tx).
	//		AddBalance(in.UserId, in.Amount, &schemaUser.UserWallet{})
	//	if err != nil {
	//		return err
	//	}
	//	// 钱包日志
	//	walletLog, err := user.NewWalletLogModel(l.ctx, tx).Create(
	//		userWallet, schemaUser.TRANSFER_TYPE_IN,
	//		in.Amount, config.TYPE_ACTIVITY_REWARD,
	//		strconv.FormatInt(in.Time, 10),
	//		"", 0,
	//	)
	//	if err != nil {
	//		return err
	//	}
	//	ret.WalletLogId = walletLog.ID
	//	// 提交事务
	//	return nil
	// })

	if err != nil {
		return nil, err
	}
	return ret, nil
}
